package lion.framework.core.conf;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import lion.dev.lang.MapJ;

public class Config extends MapJ {

	private static final long serialVersionUID = 7267010558867262534L;

	private IConfigLoader loader;

	public Config(IConfigLoader loader) {

		this.loader = loader;
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> getList(String name) {

		List<T> result = new ArrayList<>();

		Object o = this.get(name);
		if (o != null) {
			if (List.class.isAssignableFrom(o.getClass())) {
				return (List<T>) o;
			} else {
				result.add((T) o);
			}
		}

		return result;
	}

	@SuppressWarnings("unchecked")
	public <T> T getOne(String name) {

		Object o = this.get(name);
		if (o != null) {
			if (List.class.isAssignableFrom(o.getClass())) {
				List<T> list = (List<T>) o;
				if (!list.isEmpty()) {
					o = list.get(0);
				}
			}
		}
		return (T) o;
	}

	public void load() throws Exception {

		this.clear();
		Map<String, Object> map = this.loader.load();

		super.putAll(map);
	}

	public void reload() throws Exception {

		this.clear();
		this.load();
	}

	public void save() throws Exception {

		this.loader.save(this);
	}

	public <T> T select(String arg) {

		return this.loader.select(arg);
	}

}
